// 店铺数据对比模块
const { message } = window.antd;
const dayjs = window.dayjs;

// 模拟店铺列表数据
const mockStores = [
    { id: 1, name: '总店', region: '北京', type: '旗舰店' },
    { id: 2, name: '分店A', region: '上海', type: '标准店' },
    { id: 3, name: '分店B', region: '广州', type: '标准店' },
    { id: 4, name: '分店C', region: '深圳', type: '标准店' }
];

// 对比维度配置
const comparisonDimensions = [
    { key: 'orderCount', name: '订单量', unit: '单' },
    { key: 'revenue', name: '营收', unit: '元' },
    { key: 'avgOrderValue', name: '客单价', unit: '元' },
    { key: 'customerSatisfaction', name: '客户满意度', unit: '分' }
];

// 生成店铺对比数据
function generateComparisonData(storeIds, startDate, endDate, dimensions) {
    const data = {};
    const storePerformance = {
        1: { orderCount: 200, revenue: 6000, avgOrderValue: 35, customerSatisfaction: 4.8 },
        2: { orderCount: 120, revenue: 3000, avgOrderValue: 25, customerSatisfaction: 4.2 },
        3: { orderCount: 150, revenue: 4200, avgOrderValue: 28, customerSatisfaction: 4.5 },
        4: { orderCount: 80, revenue: 2400, avgOrderValue: 30, customerSatisfaction: 4.0 }
    };

    storeIds.forEach(storeId => {
        data[storeId] = dimensions.reduce((acc, dim) => {
            // 使用店铺特定的基准值
            const baseValue = storePerformance[storeId][dim.key];
            
            // 添加较小的随机波动，保持数据差异明显
            const variance = baseValue * 0.1;
            const value = baseValue + (Math.random() * variance * 2 - variance);
            
            acc[dim.key] = {
                value: dim.key === 'customerSatisfaction' ? value.toFixed(1) :
                       dim.key === 'avgOrderValue' ? value.toFixed(1) :
                       Math.floor(value),
                trend: ((Math.random() * 0.2) - 0.1).toFixed(2)
            };
            return acc;
        }, {});
    });
    return data;
}

// 分析数据差异
function analyzeDataDifference(data, dimensions) {
    const analysis = [];
    const stores = Object.keys(data);
    
    dimensions.forEach(dim => {
        const values = stores.map(storeId => ({
            storeId,
            value: parseFloat(data[storeId][dim.key].value)
        }));
        
        // 计算平均值和标准差
        const avg = values.reduce((sum, v) => sum + v.value, 0) / values.length;
        const stdDev = Math.sqrt(
            values.reduce((sum, v) => sum + Math.pow(v.value - avg, 2), 0) / values.length
        );
        
        // 识别异常值（超过1个标准差）
        values.forEach(v => {
            const deviation = Math.abs(v.value - avg);
            if (deviation > stdDev) {
                const store = mockStores.find(s => s.id === parseInt(v.storeId));
                if (!store) return;
                analysis.push({
                    dimension: dim.name,
                    storeName: store.name,
                    value: v.value,
                    difference: ((v.value - avg) / avg * 100).toFixed(1) + '%',
                    type: v.value > avg ? 'high' : 'low'
                });
            }
        });
    });
    
    return analysis;
}

// 初始化对比图表
function initComparisonCharts(data, dimensions) {
    const stores = Object.keys(data);
    dimensions.forEach(dim => {
        const chartContainer = document.getElementById(`${dim.key}ComparisonChart`);
        if (!chartContainer) return;
        
        const chart = echarts.init(chartContainer);
        const option = {
            title: { text: `${dim.name}对比` },
            tooltip: {
                trigger: 'axis',
                formatter: params => {
                    const store = mockStores.find(s => s.id === parseInt(params[0].name));
                    return `${store.name}<br/>${dim.name}: ${params[0].value}${dim.unit}`;
                }
            },
            xAxis: {
                type: 'category',
                data: stores,
                axisLabel: {
                    formatter: value => {
                        const store = mockStores.find(s => s.id === parseInt(value));
                        return store ? store.name : value;
                    }
                }
            },
            yAxis: {
                type: 'value',
                name: dim.unit,
                nameTextStyle: { padding: [0, 0, 0, 30] }
            },
            series: [{
                name: dim.name,
                type: 'bar',
                data: stores.map(storeId => data[storeId][dim.key].value),
                itemStyle: {
                    color: function(params) {
                        const value = parseFloat(data[stores[params.dataIndex]][dim.key].value);
                        const values = stores.map(s => parseFloat(data[s][dim.key].value));
                        const avg = values.reduce((a, b) => a + b, 0) / values.length;
                        return value > avg ? '#f5222d' : '#1890ff';
                    }
                },
                label: {
                    show: true,
                    position: 'top',
                    formatter: '{c}' + dim.unit
                }
            }]
        };
        chart.setOption(option);
    });
}

// 初始化店铺数据对比功能
export function initStoreComparison() {
    try {
        const contentWrapper = document.querySelector('.content-wrapper');
        contentWrapper.innerHTML = `
            <div class="store-comparison">
                <div class="comparison-header">
                    <h2 class="comparison-title">店铺数据对比</h2>
                    <div class="comparison-filters">
                        <div class="filter-group">
                            <label>选择店铺：</label>
                            <div class="store-selector">
                                ${mockStores.map(store => `
                                    <label class="store-checkbox">
                                        <input type="checkbox" value="${store.id}" ${store.id <= 2 ? 'checked' : ''}/>
                                        <span>${store.name}</span>
                                        <span class="checkmark"></span>
                                    </label>
                                `).join('')}
                            </div>
                        </div>
                        <div class="filter-group">
                            <label>对比维度：</label>
                            <div class="dimension-selector">
                                ${comparisonDimensions.map(dim => `
                                    <label class="dimension-checkbox">
                                        <input type="checkbox" value="${dim.key}" checked/>
                                        <span>${dim.name}</span>
                                        <span class="checkmark"></span>
                                    </label>
                                `).join('')}
                            </div>
                        </div>
                        <div class="filter-group">
                            <label>时间范围：</label>
                            <div class="date-selector">
                                <input type="date" class="date-input" id="startDate" />
                                <span>至</span>
                                <input type="date" class="date-input" id="endDate" />
                            </div>
                        </div>
                    </div>
                </div>
                <div class="comparison-content">
                    <div class="charts-container">
                        ${comparisonDimensions.map(dim => `
                            <div class="chart-container" id="${dim.key}ComparisonChart"></div>
                        `).join('')}
                    </div>
                    <div class="analysis-container">
                        <h3>数据差异分析</h3>
                        <div class="analysis-content" id="analysisContent"></div>
                    </div>
                </div>
            </div>
        `;

        // 设置默认日期范围（最近7天）
        const endDate = dayjs();
        const startDate = endDate.subtract(7, 'day');
        document.getElementById('startDate').value = startDate.format('YYYY-MM-DD');
        document.getElementById('endDate').value = endDate.format('YYYY-MM-DD');

        // 生成初始对比数据
        const selectedStores = [1, 2]; // 默认选择前两个店铺
        const selectedDimensions = comparisonDimensions; // 默认选择所有维度
        const comparisonData = generateComparisonData(
            selectedStores,
            startDate.toDate(),
            endDate.toDate(),
            selectedDimensions
        );

        // 初始化图表
        initComparisonCharts(comparisonData, selectedDimensions);

        // 分析数据差异
        const analysis = analyzeDataDifference(comparisonData, selectedDimensions);
        const analysisContent = document.getElementById('analysisContent');
        if (analysis.length > 0) {
            analysisContent.innerHTML = analysis.map(item => `
                <div class="analysis-item ${item.type}">
                    <span class="store-name">${item.storeName}</span>
                    <span class="dimension-name">${item.dimension}</span>
                    <span class="difference ${item.type === 'high' ? 'positive' : 'negative'}">
                        ${item.type === 'high' ? '高于' : '低于'}平均值 ${item.difference}
                    </span>
                </div>
            `).join('');
        } else {
            analysisContent.innerHTML = '<div class="no-analysis">暂无明显的数据差异</div>';
        }

        // 添加事件监听
        document.querySelectorAll('.store-checkbox input').forEach(checkbox => {
            checkbox.addEventListener('change', updateComparison);
        });
        document.querySelectorAll('.dimension-checkbox input').forEach(checkbox => {
            checkbox.addEventListener('change', updateComparison);
        });
        document.querySelectorAll('.date-input').forEach(input => {
            input.addEventListener('change', updateComparison);
        });

        function updateComparison() {
            const selectedStores = Array.from(document.querySelectorAll('.store-checkbox input:checked'))
                .map(checkbox => parseInt(checkbox.value));
            
            if (selectedStores.length < 2) {
                message.warning('请至少选择两个店铺进行对比');
                return;
            }

            const selectedDimensions = comparisonDimensions.filter(dim => 
                document.querySelector(`.dimension-checkbox input[value="${dim.key}"]`).checked
            );
            
            if (selectedDimensions.length === 0) {
                message.warning('请至少选择一个对比维度');
                return;
            }

            const startDate = dayjs(document.getElementById('startDate').value);
            const endDate = dayjs(document.getElementById('endDate').value);
            
            if (!startDate.isValid() || !endDate.isValid()) {
                message.warning('请选择有效的时间范围');
                return;
            }

            if (endDate.isBefore(startDate)) {
                message.warning('结束日期不能早于开始日期');
                return;
            }

            // 更新对比数据和图表
            const comparisonData = generateComparisonData(
                selectedStores,
                startDate.toDate(),
                endDate.toDate(),
                selectedDimensions
            );
            initComparisonCharts(comparisonData, selectedDimensions);

            // 更新数据差异分析
            const analysis = analyzeDataDifference(comparisonData, selectedDimensions);
            const analysisContent = document.getElementById('analysisContent');
            if (!analysisContent) {
                console.error('分析内容容器不存在');
                return;
            }
            if (analysis && analysis.length > 0) {
                const analysisHtml = analysis.map(item => {
                    if (!item || !item.storeName || !item.dimension || !item.difference) {
                        return '';
                    }
                    return `
                        <div class="analysis-item ${item.type || 'normal'}">
                            <span class="store-name">${item.storeName}</span>
                            <span class="dimension-name">${item.dimension}</span>
                            <span class="difference ${item.type === 'high' ? 'positive' : 'negative'}">
                                ${item.type === 'high' ? '高于' : '低于'}平均值 ${item.difference}
                            </span>
                        </div>
                    `;
                }).filter(html => html).join('');
                analysisContent.innerHTML = analysisHtml || '<div class="no-analysis">暂无有效的数据差异分析</div>';
            } else {
                analysisContent.innerHTML = '<div class="no-analysis">暂无明显的数据差异</div>';
            }
        }

    } catch (error) {
        console.error('初始化店铺数据对比功能失败:', error);
        message.error('初始化店铺数据对比功能失败，请刷新页面重试');
    }
}